package com.hqbzl.c1;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class CallBack2 {
    public static void main(String[] args) {
        Switch2<String> object = new Switch2<>();
        new Thread(() -> {
            log.debug("wait result");
            final String str = object.getEx(5000);
            log.debug("{}", str);
        }, "t1").start();
        new Thread(() -> {
            try {
                log.debug("t2");
//                object.succ(downStr);
                TimeUnit.SECONDS.sleep(2);
                log.debug("nofity");
//                synchronized (object) {
//                    object.notify();
//                }
                object.succ(null);
            } catch (Exception exception) {
                object.setException(exception);
            }
        }, "t2").start();
        final Thread thread = new Thread(() -> {
        }, "join-test");
    }

}

@Slf4j
class Switch2<T> {


    private T data;
    private Exception exception;


    public void setException(Exception exception) {
        this.exception = exception;
    }

    public Exception getException() {
        return this.exception;
    }

    public T get(long total) {
        synchronized (this) {
            final long begin = System.currentTimeMillis();
            long useTime = 0;
            while (data == null) {
                long waitTime = total - useTime;
                if (waitTime <= 0) {
                    break;
                }
                try {
                    // waitTime 如果直接等于 total 有可能会有其它的线程虚假唤醒
                    this.wait(waitTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                useTime = System.currentTimeMillis() - begin;
            }
        }
        return this.data;
    }

    // 此方法有问题
    public T getEx(long total) {
        synchronized (this) {
            final long begin = System.currentTimeMillis();
            long useTime = 0;
            while (data == null) {
                try {

                    if (useTime >= total) {
                        break;
                    }
                    // waitTime 如果直接等于 total 有可能会有其它的线程虚假唤醒
                    this.wait(total);
                    log.debug("useTime: {}", System.currentTimeMillis() - begin);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                useTime = System.currentTimeMillis() - begin;

            }
        }
        return this.data;
    }

//    public T get() {
//        return get();
//    }

    public void succ(T t) {
        synchronized (this) {
            this.data = t;
            this.notify();
        }
    }
}
